"""
态势对象关系 SQLAlchemy ORM 数据模型
"""
import uuid
from datetime import datetime
from sqlalchemy import Column, String, DateTime, Boolean, Integer, ForeignKey, CheckConstraint, Index, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID
try:
    from sqlalchemy.dialects.postgresql import JSONB
except ImportError:
    # 如果JSONB不可用，使用通用JSON类型
    from sqlalchemy import JSON as JSONB
from src.situation.database import Base


class SituationRelationship(Base):
    """态势对象关系表"""

    __tablename__ = "situation_relationships"

    # 主键和基础信息
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, comment="主键ID")
    source_object_id = Column(UUID(as_uuid=True), ForeignKey("situation_objects.id"), nullable=False, index=True, comment="源对象ID")
    target_object_id = Column(UUID(as_uuid=True), ForeignKey("situation_objects.id"), nullable=False, index=True, comment="目标对象ID")
    relationship_type = Column(String(100), nullable=False, index=True, comment="关系类型")

    # 关系层级和属性
    relationship_level = Column(Integer, default=1, nullable=False, comment="关系层级(1-5,自动计算)")
    properties = Column(JSONB, default=dict, comment="关系属性(JSONB)")
    description = Column(String(500), comment="关系描述")

    # 审计字段
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment="更新时间")
    created_by = Column(String(100), comment="创建人")
    updated_by = Column(String(100), comment="更新人")

    # 软删除
    is_deleted = Column(Boolean, default=False, nullable=False, index=True, comment="是否已删除")
    deleted_at = Column(DateTime, comment="删除时间")

    # 表约束
    __table_args__ = (
        CheckConstraint("relationship_level >= 1 AND relationship_level <= 5", name="chk_relationship_level"),
        CheckConstraint("source_object_id != target_object_id", name="chk_no_self_reference"),
        UniqueConstraint("source_object_id", "target_object_id", "relationship_type", "is_deleted", name="uq_relationship"),
        Index("idx_relationship_source", "source_object_id"),
        Index("idx_relationship_target", "target_object_id"),
        Index("idx_relationship_type", "relationship_type"),
        Index("idx_relationship_level", "relationship_level"),
    )

    def __repr__(self):
        return f"<SituationRelationship(id={self.id}, source={self.source_object_id}, target={self.target_object_id}, type={self.relationship_type})>"
